#include "Game.h"
#include "Player.h"
#include "Position.h"
#include "Console.h"
#include <mutex>
#include <thread>
#include <iostream>
#include <conio.h>
using namespace std;

Game game;
Player p2(30, 10, 2);
Player p1(10, 10, 1);
deque<Position> posQueue;
deque<char> kPQueue1;
deque<char> kPQueue2;

int prev_x_p1 = p1.pos.pos[0];
int prev_y_p1 = p1.pos.pos[1];
int prev_x_p2 = p2.pos.pos[0];
int prev_y_p2 = p2.pos.pos[1];

int Winner = 0;
mutex mtx;

void gameMainThread()
{
	game.drawGameGrid();
	while(Winner == 0)
	{
		prev_x_p1 = p1.pos.pos[0];
		prev_y_p1 = p1.pos.pos[1];
		prev_x_p2 = p2.pos.pos[0];
		prev_y_p2 = p2.pos.pos[1];

		mtx.lock();
		game.getKeyPresses(kPQueue1, kPQueue2);
		mtx.unlock();

		mtx.lock();
		game.drawPlayer(posQueue, prev_x_p1, prev_y_p1, prev_x_p2, prev_y_p2);
		mtx.unlock();		
	}
}

void p1Thread()
{
	while(Winner == 0)
	{
		if ((p1.pos.pos[0] == p2.pos.pos[0]) && (p1.pos.pos[1] == p2.pos.pos[1]))
		{
			Winner = 1;
		}
		mtx.lock();
		p1.updatePosition(kPQueue1, posQueue, p1);
		mtx.unlock();
	}
}

void p2Thread()
{
	while(Winner == 0)
	{
		if ((p1.pos.pos[0] == p2.pos.pos[0]) && (p1.pos.pos[1] == p2.pos.pos[1]))
		{
			Winner = 2;
		}
		mtx.lock();
		p2.updatePosition(kPQueue2, posQueue, p2);
		mtx.unlock();
	}
}

int main()
{
	thread t1(p1Thread);
	thread t2(p2Thread);
	thread t3(gameMainThread);
	t1.join();
	t2.join();
	t3.join();

	if(Winner == 1)
	{
		Console::gotoxy(8, 5);
		cout << "Player X has won the game!" << endl;
	}
	else if(Winner == 2)
	{
		Console::gotoxy(8, 5);
		cout << "Player O has won the game!" << endl;
	}
	cin.get();
}